//
//  AppDelegate.m
//  EZ Tracker
//
//  Created by FENGYL on 2016/10/31.
//  Copyright © 2016年 FENGYL. All rights reserved.
//

#import "AppDelegate.h"
#import "NetworkSocket.h"

#import <UserNotifications/UserNotifications.h>

@import FirebaseCore;
@import FirebaseInstanceID;
@import FirebaseMessaging;

@interface AppDelegate ()<UNUserNotificationCenterDelegate>

@property (assign, nonatomic) BOOL GoogleFIRMessagingIsLink;
@property (strong, nonatomic) UNUserNotificationCenter *userNotificationCenter;

@end

@implementation AppDelegate

-(UNUserNotificationCenter *)userNotificationCenter{
    
    if (!_userNotificationCenter) {
        _userNotificationCenter = [UNUserNotificationCenter currentNotificationCenter];
    }
    return _userNotificationCenter;
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    [self isLogin];
    
    [self pushMessageSetting];
    
//    NetworkSocket *networkSocket = [[NetworkSocket alloc]init];
//    
//    [networkSocket socketConnected];
    
    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    [[FIRMessaging messaging] disconnect];  //Firebase
    
    NSLog(@"Disconnected from FCM");
    
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    
    [self connectToFcm];
    
    //移除所有通知
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center removeAllDeliveredNotifications];
    
    //小红点归零
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark - UNUserNotificationCenterDelegate
//在展示通知前进行处理，即有机会在展示通知前再修改通知内容。
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
    //1. 处理通知
    
    NSDictionary *infoDictionary = notification.request.content.userInfo;
    
    NSLog(@"infoDictionary %@",infoDictionary);
    
    NSInteger badgeNumber = [UIApplication sharedApplication].applicationIconBadgeNumber;
    
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:badgeNumber + 1];
    
    //2. 处理完成后条用 completionHandler ，用于指示在前台显示通知的形式
    completionHandler(UNNotificationPresentationOptionAlert);
}

#pragma mark 推送
-(void)pushMessageSetting{
    
    NSInteger systemVersion = [[[UIDevice currentDevice] systemVersion] integerValue];
    
    if (systemVersion >= 10.0) {
        
        // 使用 UNUserNotificationCenter 来管理通知
        //        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        //监听回调事件
        self.userNotificationCenter.delegate = self;
        
        //iOS 10 使用以下方法注册，才能得到授权
        [self.userNotificationCenter requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound)
                                                   completionHandler:^(BOOL granted, NSError * _Nullable error) {
                                                       // Enable or disable features based on authorization.
                                                   }];
        
        //获取当前的通知设置，UNNotificationSettings 是只读对象，不能直接修改，只能通过以下方法获取
        [self.userNotificationCenter getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
            
        }];
        
        
        
    }else if (systemVersion >= 8.0){
        
        // ios8后，需要添加这个注册，才能得到授权
        if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
            UIUserNotificationType type = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
            UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type categories:nil];
            [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
            // 通知重复提示的单位，可以是天、周、月
        }
        
    }
    
    // APNs注册，获取deviceToken并上报
    [self registerAPNS:[UIApplication sharedApplication]];
    
    [FIRApp configure];
    // Add observer for InstanceID token refresh callback.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tokenRefreshNotification:)
                                                 name:kFIRInstanceIDTokenRefreshNotification object:nil];
    
}


#pragma mark APNs Register
/**
 *	向APNs注册，获取deviceToken用于推送
 *
 *
 */
- (void)registerAPNS:(UIApplication *)application {
    float systemVersionNum = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (systemVersionNum >= 10.0) {
        // 请求推送权限
        [self.userNotificationCenter requestAuthorizationWithOptions:UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (granted) {
                // granted
                NSLog(@"User authored notification.");
                // 向APNs注册，获取deviceToken
                [application registerForRemoteNotifications];
            } else {
                // not granted
                NSLog(@"User denied notification.");
            }
        }];
    } else if (systemVersionNum >= 8.0) {
        // iOS 8 Notifications
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wdeprecated-declarations"
        [application registerUserNotificationSettings:
         [UIUserNotificationSettings settingsForTypes:
          (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge)
                                           categories:nil]];
        [application registerForRemoteNotifications];
#pragma clang diagnostic pop
    } else {
        // iOS < 8 Notifications
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wdeprecated-declarations"
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
         (UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
#pragma clang diagnostic pop
    }
}


// This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
// If swizzling is disabled then this function must be implemented so that the APNs token can be paired to
// the InstanceID token.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSLog(@"APNs token retrieved: %@", deviceToken);
    
    // With swizzling disabled you must set the APNs token here.
    // [[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeSandbox];
    
    // for development
    //[[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeSandbox];
    
    // for production
    [[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeProd];
}
// [START ios_10_data_message_handling]
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
// Receive data message on iOS 10 devices while app is in the foreground.
- (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {
    // Print full message
    NSLog(@"%@", [remoteMessage appData]);
}
#endif
// [END ios_10_data_message_handling]

// [START refresh_token]
- (void)tokenRefreshNotification:(NSNotification *)notification {
    // Note that this callback will be fired everytime a new token is generated, including the first
    // time. So if you need to retrieve the token as soon as it is available this is where that
    // should be done.
    NSLog(@"tokenRefreshNotification");
    
    NSString *refreshedToken = [[FIRInstanceID instanceID] token];
    NSLog(@"InstanceID token: %@", refreshedToken);
    
    // Connect to FCM since connection may have failed when attempted before having a token.
    [self connectToFcm];
    
    // TODO: If necessary send token to application server.
}
// [END refresh_token]

// [START connect_to_fcm]
- (void)connectToFcm {
    NSLog(@"connectToFcm func");
    if(_GoogleFIRMessagingIsLink)
    {
        return;
    }
    NSLog(@"connectToFcm func into");
    _GoogleFIRMessagingIsLink = YES;
    [[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
        if (error != nil) {
            NSLog(@"Unable to connect to FCM. %@", error);
        } else {
            NSLog(@"Connected to FCM.");
        }
    }];
}
// [END connect_to_fcm]


#pragma mark 判断是否登录
-(void)isLogin{
    
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    
    BOOL isLogin = [userDefaults boolForKey:@"isLogin"];
    
    if (isLogin && isLogin == YES) {
        
        UIStoryboard * storyboard = [UIStoryboard storyboardWithName:@"MainView" bundle:[NSBundle mainBundle]];
        
        UINavigationController * navigationController = [storyboard instantiateViewControllerWithIdentifier:@"MainViewNavigation"];
        
        self.window.rootViewController = navigationController;
        
    }
    
}

@end
